<?php

namespace App\Admin\Controllers;

use App\Admin\Requests\VueAdminUserRouterRequest;
use App\Admin\Resources\VueAdminUserRouterResource;
use App\Admin\Models\VueAdminUserRouter;
use App\Admin\Models\SystemModel;
use App\Admin\Utils\Admin;
use Illuminate\Http\Request;

class VueAdminUserRouterController extends Controller
{
    public function store(VueAdminUserRouterRequest $request, VueAdminUserRouter $vueAdminUserRouter)
    {
        $inputs = $request->validated();
        $inputs['id'] = $vueAdminUserRouter->getVueAdminUserRouterInsertId(Admin::user()->id);
        $inputs['is_custom'] = 1;
        $inputs['user_id'] = Admin::user()->id;
        $vueAdminUserRouter = $vueAdminUserRouter->create($inputs);

        return $this->created(
            VueAdminUserRouterResource::make($vueAdminUserRouter)
        );
    } 

    public function update(VueAdminUserRouterRequest $request, VueAdminUserRouter $vueAdminUserRouter)
    {
        $inputs = $request->validated();
        $vueAdminUserRouter->update($inputs);

        return $this->created(
            VueAdminUserRouterResource::make($vueAdminUserRouter)
        );
    }

    public function edit(VueAdminUserRouter $vueAdminUserRouter)
    {
        return $this->ok(
            VueAdminUserRouterResource::make($vueAdminUserRouter)
            ->for(VueAdminUserRouterResource::FOR_EDIT)
            ->additional($this->formData($vueAdminUserRouter->id))
        );
    }

    public function index(VueAdminUserRouter $vueAdminUserRouter)
    {
        return $this->ok($vueAdminUserRouter->getVueAdminUserRouterList());
    }

    public function destroy(VueAdminUserRouter $vueAdminUserRouter)
    {
        $vueAdminUserRouter->delete();
        return $this->noContent();
    }

    public function batchUpdate(Request $request, VueAdminUserRouter $vueAdminUserRouter)
    {
        $vueAdminUserRouter->saveOrder($request->input('_order', []));

        return $this->created();
    }

    /**
     * 返回添加和编辑表单时用到的选项数据
     *
     * @param int $exceptRouterId 要排除的 路由配置 id，编辑表单用到
     *
     * @return array
     */
    protected function formData($exceptRouterId = null)
    {
        $model = app(VueAdminUserRouter::class);
        $includeRouterId = $model->getVueAdminUserRouterId();
        $vueAdminUserRouters = $model->treeInclude($includeRouterId)
            ->treeExcept($exceptRouterId ?? 0)
            ->toTree();
        $systemModels = SystemModel::withTrashed()
            ->where('parent_id', 0)
            ->get(['id', 'name'])
            ->toArray();
        return [
            'vue_routers' => $vueAdminUserRouters,
            'system_models' => $systemModels,
        ];
    }

    public function create()
    {
        return $this->ok($this->formData());
    }
}
